<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model='search' style="width: 300px;" class="filter-item" placeholder="配置项名称">
      </el-input>
      <el-button class="filter-item" @click="handleCreate" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-edit">{{$t('table.add')}}</el-button>
      <el-button class="filter-item" @click="publishAll" type="primary" :loading="publishLoading" v-waves icon="el-icon-upload">{{$t('table.publishAll')}}</el-button>
      <el-button class="filter-item" @click="handleDownload" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download">{{$t('table.export')}}</el-button>
    </div>

    <el-table :data="searchData" :default-sort="{prop: 'itemName', order: 'descending'}" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label='ID' width="50">
        <template slot-scope="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column prop="itemName" sortable label="配置项名称" width="220"  align="center">
        <template slot-scope="scope">
          {{scope.row.itemName}}
        </template>
      </el-table-column>
      <el-table-column label="配置项值" align="center">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" class="edit-input" size="small" v-model="scope.row.value"></el-input>
          <span v-else>{{ scope.row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="120" align="center">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" class="edit-input" size="small" v-model="scope.row.remark"></el-input>
          <span v-else>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="70" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.releaseStatus | statusFilter">{{getStatusName(scope.row.releaseStatus)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后发布人" width="100" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="100" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.releaseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" width="290" align="center"> 
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="publish(scope.row)">{{$t('table.publish')}}</el-button>
          <el-button type="info" size="mini" @click="revert(scope.row)">{{$t('table.revert')}}</el-button>
          <template v-if="scope.row.edit">
            <el-button type="success" @click="confirmEdit(scope.row)" size="mini">保存</el-button>
            <el-button type="warning" @click="cancelEdit(scope.row)" size="mini" >撤销</el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click='Edit(scope.row)' size="mini">{{$t('table.edit')}}</el-button>
            <el-button type="danger" @click="remove(scope.row)" size="mini" >{{$t('table.delete')}}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="新建配置项" :visible.sync="dialogFormVisible">
      <el-form :rules="configRules" ref="dataForm" :model="temp" label-position="left" label-width="100px" >
        <el-form-item label="配置项名称" prop="itemName">
          <el-input v-model="temp.itemName"></el-input>
        </el-form-item>
        <el-form-item label="配置项值" prop="value">
          <el-input v-model="temp.value"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="createConfig">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadConfigs, getConfigLst, updateConfig, removeConfig, releaseConfig, releaseConfigs, rollbackConfig, createConfig } from '@/api/config'
// import { getConfigLst, updateConfig, removeConfig, releaseConfig, releaseConfigs, rollbackConfig, createConfig } from '@/api/config'
import { success, info_msg, warning_msg } from '@/utils/notify'
import { check } from '@/utils/resCheck'
import waves from '@/directive/waves'

export default {
  directives: {
    waves
  },
  data() {
    return {
      listQuery: {
        teamName: 'o2o',
        propertyName: 'db-conf',
        username: this.$store.state.user.name
      },
      search: '',
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      downloadLoading: false,
      publishLoading: false,
      path: this.$route.path,
      temp: {
        itemName: '',
        value: '',
        remark: ''
      },
      configRules: {
        itemName: [{ required: true, trigger: 'blur', message: '请输入配置项名称' }]
      }
    }
  },
  watch: {
    '$route.path': function() {
      this.fetchData()
    }
  },
  filters: {
    statusFilter(status) {
      const roleMap = {
        1: 'success',
        0: 'info'
      }
      return roleMap[status]
    }
  },
  created() {
    const info = this.$route.path.split('/')
    this.listQuery.teamName = info[2]
    this.listQuery.propertyName = info[3]
    this.fetchData()
  },
  computed: {
    searchData: function() {
      var search = this.search
      if (search) {
        return this.list.filter(function(product) {
          return Object.keys(product).some(function(key) {
            if (key === 'itemName') {
              return String(product[key]).toLowerCase().indexOf(search) > -1
            }
          })
        })
      }
      return this.list
    }
  },
  methods: {
    getStatusName: function(status) {
      if (status) {
        return '发布'
      }
      return '未发布'
    },
    Edit(row) {
      row.edit = true
    },
    cancelEdit(row) {
      row.value = row.originalValue
      row.remark = row.originalRemark
      row.edit = false
      this.$message({
        message: '编辑已撤销，变更已还原',
        type: 'warning'
      })
    },
    confirmEdit(row) {
      row.edit = false
      row.originalValue = row.value
      row.originalRemark = row.remark
      updateConfig(row).then(response => {
        if (check(this, response) !== true) {
          return
        }
        row.releaseStatus = 0
        success(this, '保存成功')
      })
    },
    publish(row) {
      const tempData = Object.assign({}, row)
      if (tempData.releaseStatus === 1) {
        warning_msg(this, '已发布,无需重复发布')
        return
      }
      tempData.username = this.$store.state.user.name
      releaseConfig(tempData).then(response => {
        if (check(this, response) !== true) {
          return
        }
        this.fetchData()
        success(this, '发布成功')
      })
    },
    publishAll() {
      releaseConfigs(this.listQuery).then(response => {
        if (check(this, response) !== true) {
          return
        }
        this.fetchData()
        success(this, '发布成功')
      })
    },
    revert(row) {
      const tempData = Object.assign({}, row)
      tempData.username = this.$store.state.user.name
      tempData.username = 'admin'
      rollbackConfig(tempData).then(response => {
        if (check(this, response) !== true) {
          return
        }
        this.fetchData()
        success(this, '回滚成功')
      })
    },
    remove(row) {
      this.$confirm('此操作将永久删除该配置项,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // row.username = this.$store.state.user.name
        const tempData = Object.assign({}, row)
        tempData.username = this.$store.state.user.name
        removeConfig(tempData).then(response => {
          if (check(this, response) !== true) {
            return
          }
          this.fetchData()
          success(this, '删除成功')
        })
      }).catch(() => {
        info_msg(this, '已取消删除')
      })
    },
    fetchData() {
      const info = this.$route.path.split('/')
      this.listQuery.teamName = info[2]
      this.listQuery.propertyName = info[3]
      this.listLoading = true
      getConfigLst(this.listQuery).then(response => {
        this.list = response.configLst.map(v => {
          this.$set(v, 'edit', false)
          v.originalRemark = v.remark
          if (v.releaseStatus === 0) {
            v.value = v.tempValue
          }
          v.originalValue = v.value
          return v
        })
        this.listLoading = false
      })
    },
    handleDownload() {
      downloadConfigs(this.listQuery)
    },
    handleCreate() {
      this.temp = {}
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createConfig() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign(this.listQuery, this.temp)
          createConfig(tempData).then(response => {
            if (check(this, response) !== true) {
              this.dialogFormVisible = false
              return
            }
            this.fetchData()
            this.dialogFormVisible = false
            success(this, '创建成功')
          })
        }
      })
    }
  }
}
</script>

